using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Text;
using System.Windows.Forms;
using Firestarter.DB.Schema.BO;
using FireStarterModeller.BO;
using Habanero.Base;
using Habanero.BO.ClassDefinition;
using Habanero.DB;
using Habanero.Faces.Base;
using Habanero.Faces.Win;

namespace Firestarter.DB.Schema.UI
{
    public class SchemaInvestigator : UserControlWin, IFormControl
    {
        private IDataGridView _collectionsDataGridView;
        private IDataGridView _detailsDataGridView;
        private IDatabaseConnection _databaseConnection;
        private DatabaseConnectionInfo _databaseConnectionInfo;

        public SchemaInvestigator()
        {
            IControlFactory factory = GlobalUIRegistry.ControlFactory;
            PanelBuilder panelBuilder = new PanelBuilder(factory);
            
            IPanel databaseConnectionPanel = SetupDatabaseConnectionPanel(panelBuilder);

            IGroupBox groupBox = SetupMainGroupBox(factory);

            BorderLayoutManager layoutManager = factory.CreateBorderLayoutManager(this);
            layoutManager.AddControl(databaseConnectionPanel, BorderLayoutManager.Position.North);
            layoutManager.AddControl(groupBox, BorderLayoutManager.Position.Centre);

            
        }

        private IGroupBox SetupMainGroupBox(IControlFactory factory)
        {
            IGroupBox groupBox = factory.CreateGroupBox();
            groupBox.Text = "Database Schema";
            BorderLayoutManager layoutManager = factory.CreateBorderLayoutManager(groupBox);

            IButton button = factory.CreateButton("Refresh");
            button.Click += delegate { RefreshDatabase(); };
            layoutManager.AddControl(button, BorderLayoutManager.Position.North);

            IPanel panel = SetupSchemaDataGridsPanel(factory);
            layoutManager.AddControl(panel, BorderLayoutManager.Position.Centre);

            return groupBox;
        }

        private IPanel SetupSchemaDataGridsPanel(IControlFactory factory)
        {
            IPanel panel = factory.CreatePanel();
            BorderLayoutManager layoutManager = factory.CreateBorderLayoutManager(panel);

            _collectionsDataGridView = factory.CreateDataGridView();
            _collectionsDataGridView.SelectionChanged += delegate(object sender, EventArgs e)
            {
                try
                {
                    if (_collectionsDataGridView.CurrentRow == null) return;
                    string collectionName = Convert.ToString(_collectionsDataGridView.CurrentRow.Cells[0].Value);
                    LoadSchemaCollection(collectionName);
                }
                catch (Exception ex)
                {
                    GlobalRegistry.UIExceptionNotifier.Notify(ex, "", "");
                }
            };
            layoutManager.AddControl(_collectionsDataGridView, BorderLayoutManager.Position.West, true);

            _detailsDataGridView = factory.CreateDataGridView();
            layoutManager.AddControl(_detailsDataGridView, BorderLayoutManager.Position.Centre);

            return panel;
        }

        private void LoadSchemaCollection(string collectionName)
        {
            if (_databaseConnection == null) return;
            DataTable dataTable = GetSchemaDataTable(collectionName);
            _detailsDataGridView.DataSource = null;
            _detailsDataGridView.Columns.Clear();
            _detailsDataGridView.DataSource = dataTable;
        }

        private void RefreshDatabase()
        {
            try
            {
                DatabaseConfig databaseConfig = _databaseConnectionInfo.CreateDatabaseConfig();
                _databaseConnection = databaseConfig.GetDatabaseConnection();
                DataTable dataTable = GetSchemaDataTable("MetaDataCollections");
                _collectionsDataGridView.DataSource = dataTable;
            }
            catch (Exception ex)
            {
                GlobalRegistry.UIExceptionNotifier.Notify(ex, "", "");
            }
        }

        private DataTable GetSchemaDataTable(string collectionName)
        {
            DbConnection connection = GetDbConnection();
            if (connection == null) return new DataTable();
            connection.Open();
            return connection.GetSchema(collectionName);

        }

        private DbConnection GetDbConnection()
        {
            if (_databaseConnection == null) return null;
            return _databaseConnection.GetConnection() as DbConnection;
        }

        private IPanel SetupDatabaseConnectionPanel(PanelBuilder panelBuilder)
        {
            IPanelInfo panelInfo = panelBuilder.BuildPanelForForm(ClassDef.Get<DatabaseConnectionInfo>().GetUIDef("default").UIForm);
            _databaseConnectionInfo = CreateDefaultDatabaseConnectionInfo();
            panelInfo.BusinessObject = _databaseConnectionInfo;
            IPanel panel = panelInfo.Panel;
            PanelInfo.FieldInfo fieldInfo = panelInfo.FieldInfos[panelInfo.FieldInfos.Count - 1];
            panel.Height = fieldInfo.InputControl.Bottom + 5;
            return panel;
        }

        private DatabaseConnectionInfo CreateDefaultDatabaseConnectionInfo()
        {
            DatabaseConnectionInfo databaseConnectionInfo = new DatabaseConnectionInfo();
            databaseConnectionInfo.Vendor = "SQL Server";
            databaseConnectionInfo.Server = "localhost";
            databaseConnectionInfo.Database = "orderentry";
            databaseConnectionInfo.UserName = "sa";
            databaseConnectionInfo.Password = "sa";
            return databaseConnectionInfo;
        }

        public void SetForm(IFormHabanero form)
        {
        }
    }
}
